// pages/enroll/enroll.js
// pages/group/group.js
const Promise = require('../../lib/promiseEs6Fix')
const app = getApp();
const WxParse = require('../../wxParse/wxParse.js');
const amapFile = require('../../lib/amap-wx.js');
Page({
  data: {
    /**域名 */
    hosts: '',

    /**地区数据 */
    province: ['美国', '中国', '巴西', '日本', '随便来一个'],
    city: [],
    district: [],
    company: [],
    curProvinceId: 0,
    curProvinceName: '未知',
    curCityId: 0,
    curCityName: '未知',
    curDistrictId: 0,
    curDistrictName: '未知',
    curCompanyId: 0,
    curCompanyName: '',

    //高德地图获取的位置信息
    amapLocation:{
      country  : '',
      province : '',
      city     : '',
      district : '',
    },
    is_by_handle:0,//用户是否自己手动选择位置


    targetTime : {
      year: 2018,
      month: 6,
      day: 1,
      hour: 1,
      minute: 1,
      second: 1,
    },
    leftTime:{
      day:0,
      hour:0,
      minute:0,
      second:0
    },
  

    /**接受页面传递参数 */
    id: 0,  //活动id



  },
  onLoad: function (options) {
    let that = this;
    that.getAmap();
    wx.request({
      url: app.globalData.hosts + '/index/exhibition/detail/id/' + options.id,
      header: {
        'X-Requested-With': 'XMLHttpRequest',
        'authentication': app.globalData.token
      },
      data: {},
      method: 'GET',
      success: function (res) {
        let target = res.data.data.targetTime;
        let targetTime = {
          year: parseInt(target[0]),
          month: parseInt(target[1]),
          day: parseInt(target[2]),
          hour: parseInt(target[3]),
          minute: parseInt(target[4]),
          second: parseInt(target[5]),
        }; 
        that.setData({
          targetTime:targetTime
        });
        that.leftTimer();
        //WxParse.wxParse('article', 'html', res.data.msg, that, 5);
      }
    });

    this.getProvinces();
    this.setData({
      id: options.id, //详情id 
      hosts: app.globalData.hosts
    });
    
    //但是用户拒绝一次之后 会在一段长时间内 不显示
    wx.getSetting({
      success: function (res) {
        console.log(res);
        if (!res.authSetting['scope.userLocation']) { 
          wx.authorize({
            scope: 'scope.userLocation',
          });
        }
      }
    });
    
    
    
  },
  getProvinces: function () {
    let that = this;
    wx.request({
      url: app.globalData.hosts + '/index/api/getProvince',
      header: {
        'X-Requested-With': 'XMLHttpRequest',
        'authentication': app.globalData.token
      },
      success: function (res) {        
        res = res.data.data;
        //console.log(res.data);
        that.setData({
          province: res.data,
          curProvinceName: res.data[0].name,
          curProvinceId: res.data[0].id
        });
        that.getCities(res.data[0].id);
        
      }
    });
  },
  getCities: function (provinceId) {
    let that = this;
    wx.request({
      url: app.globalData.hosts + '/index/api/getCities',
      header: {
        'X-Requested-With': 'XMLHttpRequest',
        'authentication': app.globalData.token
      },
      data: {
        provinceId: provinceId
      },
      success: function (res) {
        res = JSON.parse(res.data.msg);
        if (res.status) {
          that.setData({
            city: res.data,
            curCityName: res.data[0].name,
            curCityId: res.data[0].id
          });

          that.getDistrict(res.data[0].id);
        } else {
          //没有数据，设置默认值 默认-1 比较好 因为为空的时候 也会变成0 不易辨别  0表示根本没选  -1表示选了 但是没有值  操作过快就会产生0
          that.setData({
            curCityName: '当前省没有下级数据（可以不选）',
            curCityId: '-1'
          });
          that.getDistrict('-1');
        }
        //console.log({ "position:": "获取城市", "res": res });
      },
    });
  },
  getDistrict: function (cityId) {
    let that = this;
    wx.request({
      url: app.globalData.hosts + '/index/api/getDistricts',
      header: {
        'X-Requested-With': 'XMLHttpRequest',
        'authentication': app.globalData.token
      },
      data: {
        cityId: cityId
      },
      success: function (res) {
        res = JSON.parse(res.data.msg);
        if (res.status) {
          //console.log(res.data);
          that.setData({
            district: res.data,
            curDistrictName: res.data[0].name,
            curDistrictId: res.data[0].id
          });
          that.getCompany(res.data[0].id);
        } else {
          that.setData({
            curDistrictName: '当前市没有下级数据（可以不选）',
            curDistrictId: '-1'
          });
        }


        //尝试自动判断位置
        if (!that.data.is_by_handle){
          that.setProvince();
          that.setCity();
        }
      
      },

    });
  },
  //要保证操作到这一步 不然不允许跳转 
  getCompany: function (districtId) {
    let that = this;
    wx.request({
      url: app.globalData.hosts + '/index/api/getCompany',
      header: {
        'X-Requested-With': 'XMLHttpRequest',
        'authentication': app.globalData.token
      },
      data: {
        districtId: districtId
      },
      success: function (res) {
        let data = res.data.data;
        if (data.length > 0) {
          that.setData({
            company: data,
            curCompanyName: data[0].company_name,
            curCompanyId: data[0].id
          });
        } else {
          that.setData({
            company: data,
            curCompanyName: '',
            curCompanyId: '0',
          });
        }
      }
    })
  },
  bindProvinceChange: function (e) {
    let that = this;
    //console.log('picker发送选择改变，携带值为', e.detail.value)
    //console.log(that.data."4"
    this.data.is_by_handle = 1;
    let item = this.data.province[e.detail.value];
    this.setData({
      provinceId: e.detail.value,
      curProvinceName: item.name,
      curProvinceId: item.id
    });
    this.getCities(item.id);
  },
  bindCityChange: function (e) {
    if (e.detail.value == -1) {
      return;
    }
    this.data.is_by_handle = 1;
    //console.log(e.detail.value);
    let item = this.data.city[e.detail.value];
    this.setData({
      curCityName: item.name,
      curCityId: item.id
    });
    this.getDistrict(item.id);
  },
  bindDistrictChange: function (e) {
    if (e.detail.value == -1) {
      return;
    }
    let item = this.data.district[e.detail.value];
    console.log(item);
    this.setData({
      curDistrictName: item.name,
      curDistrictId: item.id
    });
    this.getCompany(item.id);
  },
  bindCompanyChange: function (e) {

    let item = this.data.company[e.detail.value];
    this.setData({
      curCompanyName: item.company_name,
      curCompanyId: item.id
    });
  },


  //从高德获取到的地址信息 设置picker的值 并且调整联动值
  setProvince:function(){
    //判断如果已经是相等 那么就不要继续获取了 
    if (this.data.amapLocation.province == this.data.curProvinceName) return;
    for(let i = 0;i<this.data.province.length;i++){
      if (this.data.province[i].name == this.data.amapLocation.province){
        console.log(this.data.province[i]);

        let item = this.data.province[i];
        this.setData({
          provinceId:i,
          curProvinceName: item.name,
          curProvinceId: item.id
        });
        console.log({ setProvince: this.data.amapLocation.province });
        this.getCities(item.id);
        return;
      }
    }
  },
  setCity:function(){
    if (this.data.amapLocation.city == this.data.curCityName) return; 
    for(let i = 0;i<this.data.city.length;i++){
      if (this.data.city[i].name == this.data.amapLocation.city){
        let item = this.data.city[i];
        this.setData({
          curCityName: item.name,
          curCityId: item.id
        });
        this.getDistrict(item.id);
        console.log({setCities:this.data.amapLocation.city});
        return;
      }
    }

  },
  setDistrict:function(district_name){

  },


  //从高德地图上获取位置信息
  getAmap:function(){
    //console.log('getAmap.begin');

    var that = this;
    var myAmapFun = new amapFile.AMapWX({ key: '57ebe9902f8a9beb751934d02c676c28' });
    myAmapFun.getRegeo({
      success: function (data) {
        //成功回调
        let location = data[0]['regeocodeData']['addressComponent'];
        let country = location.country;
        let province = location.province;
        let city =  location.city;
        let district = location.township;
        //console.log({country:country,province:province,city:city,district:district});
        let amapLocation = { country: country, province: province, city: city, district: district };
        
        that.setData({
          amapLocation:amapLocation
        });
      },
      fail: function (info) {
        //失败回调
        console.log({locationfail:info});
      }
    });

  },
  formSubmit: function (e) {
    console.log("报名下一步");
    //报名的数据还是先保留在本地 然后一次性提交
    //选择用一次性提交 ，因为如果分开提交，还要处理用户第二次进来的时候 数据的显示问题 一次性提交 就让用户自己重新填写 如果退出的话
    //保存表单数据
    //这一步要验证用户的手机号码 然后再保存 当填写的手机号与本地存储的不一致说明有更改，仍然需要验证
    //短信验证最后加上去
    //已经报名的 这里不能再提交了  只有进入个人中心去修改了
    let formData = e.detail.value;
    if (this.data.curCityId == -1) {
      this.data.curCityName = '未知';
    }
    if (this.data.curDistrictId == -1) {
      this.data.curDistrictName = '未知';
    }
    let sign_data = {
      'province_id': this.data.curProvinceId,
      'province_name': this.data.curProvinceName,
      'city_id': this.data.curCityId,
      'city_name': this.data.curCityName,
      'district_id': this.data.curDistrictId,
      'district_name': this.data.curDistrictName,
      'company_one_id': this.data.curCompanyId,
      'company_name': this.data.curCompanyName,
      'mobile': formData.mobile,
      'real_name': formData.real_name,
      'exhibition_id': this.data.id,
      'invite_code': formData.invite_code,
    };
    
    //提交前的检查
    wx.request({
      url: app.globalData.hosts + '/index/exhibition/beforeEnroll',
      header: {
        'X-Requested-With': 'XMLHttpRequest',
        'authentication': app.globalData.token
      },
      method: 'POST',
      data: sign_data,
      success: function (res) {
        console.log(res);
        if (res.data.code == 1) {
          wx.setStorageSync('sign_data', sign_data);
          wx.navigateTo({
            url: '/pages/home/stepTwo/stepTwo',
          });
        } else {
          wx.showToast({
            title: res.data.msg,
            mask: true,
            icon: 'none'
          });
        }
      }
    });

  
  }
  ,



  //倒计时
  leftTimer: function (){
    let leftTime = (new Date(this.data.targetTime.year, this.data.targetTime.month - 1, this.data.targetTime.day, this.data.targetTime.hour, this.data.targetTime.minute, this.data.targetTime.second)) - (new Date()); //计算剩余的毫秒数 
    let days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10); //计算剩余的天数 
    let hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10); //计算剩余的小时 
    let minutes = parseInt(leftTime / 1000 / 60 % 60, 10);//计算剩余的分钟 
    let seconds = parseInt(leftTime / 1000 % 60, 10);//计算剩余的秒数 
    days = this.checkTime(days);
    hours = this.checkTime(hours);
    minutes = this.checkTime(minutes);
    seconds = this.checkTime(seconds);
    setTimeout(this.leftTimer, 1000);
    let ltime = {day:days,hour:hours,minute:minutes,second:seconds};
    this.setData({
      leftTime:ltime
    });
  },
  checkTime:function(i){
    //将0-9的数字前面加上0，例1变为01 
    if (i < 10) {
      i = "0" + i;
    }
    return i;
  }
});